package com.sinosoft.call.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sinosoft.call.entity.model.CallConfig;
import com.sinosoft.call.service.CallService;

@Service("restCallService")
public class RestCallService implements CallService {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private static Pattern p = Pattern.compile("\\{[^\\{]*\\}");
	private HttpHeaders headers;
	@Autowired
	private RestTemplate restTemplate;

	@Override
	public JSONObject callService(CallConfig callConfig, JSON param) {
		String data = JSON.toJSONString(param,SerializerFeature.WriteMapNullValue);
//		if(param instanceof JSONObject){
//			data = JSONObject.toJSONString(param,SerializerFeature.WriteMapNullValue);
//		}else{
//			data = JSONArray.toJSONString(param,SerializerFeature.WriteMapNullValue);
//		}


		String rsqStr;
		ResponseEntity<String> obj;
		HttpEntity<String> formEntity = new HttpEntity<String>(data,
				getHttpHeaders());
		if (callConfig.getCallurl().indexOf("{") >= 0) {
			Map<String, String> pathValue = getPathValue(
					callConfig.getCallurl(), param);
			obj = restTemplate.exchange(callConfig.getCallurl(),
					HttpMethod.valueOf(callConfig.getMenthod()), formEntity,
					String.class, pathValue);
		} else {
			obj = restTemplate.exchange(callConfig.getCallurl(),
					HttpMethod.valueOf(callConfig.getMenthod()), formEntity,
					String.class);
		}
		
		rsqStr = obj.getBody();

		return getFormatResponseXML(rsqStr, callConfig.getCode(),
				callConfig.getPrintflag());
	}

	public HttpHeaders getHttpHeaders() {
		if (headers == null) {
			headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		}
		return headers;
	}

	public Map<String, String> getPathValue(String url, JSON params) {
		JSONObject param = (JSONObject) params;
		Map<String, String> re = new HashMap<String, String>();
		Matcher q = p.matcher(url);
		while (q.find()) {
			String key = q.group(0).replaceAll("\\{|\\}", "");
			re.put(key, param.getString(key));
		}
		return re;
	}

	public static void main(String[] args) {

		System.out.println(HttpMethod.valueOf("PUT"));
	}
}
